package com.chj.kmp.test;

public class CodeTest_02_Manacher_ShortestEnd {

	public static char[] manacherString(String str) {
		char[] charArr = str.toCharArray();
		char[] res = new char[str.length() * 2 + 1];
		int index = 0;
		for (int i = 0; i < res.length; i++) {
			res[i] = (i & 1) == 0 ? '#' : charArr[index++];
		}
		return res;
	}

	public static String shortestEnd(String str) {
		if (str == null || str.length() < 1) {
			return null;
		}

		char[] ss = manacherString(str);
		int[] pArr = new int[ss.length];
		int mid = -1;
		int right = -1;
		int end = 0;
		for (int i = 0; i < ss.length; i++) {
			if (i >= right) {
				while (i + pArr[i] < ss.length && i - pArr[i] > -1) {
					if (ss[i + pArr[i]] == ss[i - pArr[i]]) {
						pArr[i]++;
					} else {
						break;
					}
				}

				if (i + pArr[i] > right) {
					right = i + pArr[i];
					mid = i;
				}
			}

			if (i < right) {
				int ii = pArr[2 * mid - i];
				int ri = right - i;
				if (ii > ri) {
					pArr[i] = ri;
				} else if (ii < ri) {
					pArr[i] = ii;
				} else {
					while (i + pArr[i] < ss.length && i - pArr[i] > -1) {
						if (ss[i + pArr[i]] == ss[i - pArr[i]]) {
							pArr[i]++;
						} else {
							break;
						}
					}

					if (i + pArr[i] > right) {
						right = i + pArr[i];
						mid = i;
					}
				}
			}

			if (right == ss.length) {
				end = pArr[i];
				break;
			}

		}

		System.out.println(end);
		char[] res = new char[str.length() - end + 1];
		for (int i = 0; i < res.length; i++) {
			res[res.length - 1 - i] = ss[i * 2 + 1];
		}

		return String.valueOf(res);
	}

	public static void main(String[] args) {
		String str2 = "abcd12399321";
		System.out.println(shortestEnd(str2));
	}

}
